package com.qianya.oa.controller.system;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qianya.oa.common.annotation.Log;
import com.qianya.oa.common.constant.UserConstants;
import com.qianya.oa.common.core.controller.BaseController;
import com.qianya.oa.common.core.domain.AjaxResult;
import com.qianya.oa.common.core.domain.entity.SysDept;
import com.qianya.oa.common.core.domain.entity.SysRole;
import com.qianya.oa.common.core.domain.entity.SysUser;
import com.qianya.oa.common.core.page.TableDataInfo;
import com.qianya.oa.common.core.text.Convert;
import com.qianya.oa.common.enums.BusinessType;
import com.qianya.oa.common.utils.ShiroUtils;
import com.qianya.oa.common.utils.StringUtils;
import com.qianya.oa.common.utils.poi.ExcelUtil;
import com.qianya.oa.domain.SysPost;
import com.qianya.oa.service.ISysDeptService;
import com.qianya.oa.service.SysPostService;
import com.qianya.oa.service.ISysRoleService;
import com.qianya.oa.service.SysUserService;
import com.qianya.oa.shiro.service.SysPasswordService;
import com.qianya.oa.shiro.util.AuthorizationUtils;
import com.qianya.oa.util.CommonResult;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息
 * 
 * @author qianya
 */
@Controller
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    private String prefix = "system/user";

    @Autowired
    private SysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private SysPostService postService;

    @Autowired
    private SysPasswordService passwordService;
    @Resource
    private ISysDeptService iSysDeptService;

    @RequiresPermissions("system:user:view")
    @GetMapping()
    public String user()
    {
        return prefix + "/user";
    }

    @RequiresPermissions("system:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String message = userService.importUser(userList, updateSupport, getLoginName());
        return AjaxResult.success(message);
    }

    @RequiresPermissions("system:user:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("roles", roleService.selectRoleAll().stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostAll());
        return prefix + "/add";
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysUser user) {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName())))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(getLoginName());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @RequiresPermissions("system:user:edit")
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        userService.checkUserDataScope(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        mmap.put("user", userService.selectUserById(userId));
        mmap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return error("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getLoginName());
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return toAjax(userService.updateUser(user));
    }

    @RequiresPermissions("system:user:resetPwd")
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        mmap.put("user", userService.selectUserById(userId));
        return prefix + "/resetPwd";
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        if (userService.resetUserPwd(user) > 0)
        {
            if (ShiroUtils.getUserId().longValue() == user.getUserId().longValue())
            {
                setSysUser(userService.selectUserById(user.getUserId()));
            }
            return success();
        }
        return error();
    }

    /**
     * 进入授权角色页
     */
    @GetMapping("/authRole/{userId}")
    public String authRole(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        SysUser user = userService.selectUserById(userId);
        // 获取用户所属的角色列表
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        mmap.put("user", user);
        mmap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return prefix + "/authRole";
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PostMapping("/authRole/insertAuthRole")
    @ResponseBody
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return success();
    }

    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        if (ArrayUtils.contains(Convert.toLongArray(ids), getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(ids));
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(SysUser user)
    {
        return userService.checkLoginNameUnique(user.getLoginName());
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(SysUser user)
    {
        return userService.checkPhoneUnique(user);
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(SysUser user)
    {
        return userService.checkEmailUnique(user);
    }

    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        return toAjax(userService.changeStatus(user));
    }

//    ----------------------------新版分割线-------------------------------------
    @PostMapping("/listVue")
    @ResponseBody
    public CommonResult<?> listVue(@RequestParam(required = false,name = "id") Integer id,@RequestParam("pageNum") Integer pageNum,@RequestParam("pageSize")Integer pageSize,@RequestParam(value = "userName",required = false)String userName,@RequestParam(value = "phone",required = false)String phone) {
        List<SysUser> list;
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        sysUser.setPhonenumber(phone);
        PageHelper.startPage(pageNum,pageSize);
            if (id == null) {
            list = userService.selectUserList(sysUser);
            }else{
            sysUser.setDeptId(Long.valueOf(id));
                list = userService.selectUserList(sysUser);
            }
//        if (getSysUser().isAdmin()){
//        if (id == null) {
//            list = userService.selectUserList(new SysUser());
//            }else{
//            SysUser sysUser = new SysUser();
//            sysUser.setDeptId(Long.valueOf(id));
//                list = userService.selectUserList(sysUser);
//            }
//        }else{
//            SysUser sysUser = new SysUser();
//            if (id == null){
//                sysUser.setDeptId(getSysUser().getDeptId());
//            }else {
//                sysUser.setDeptId(Long.valueOf(id));
//            }
//            list = userService.selectUserList(sysUser);
//        }
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        return CommonResult.success(pageInfo);
    }

    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/removeVue")
    @ResponseBody
    public  CommonResult<?>  removeVue(@RequestParam("ids") String ids)
    {
        if (ArrayUtils.contains(Convert.toLongArray(ids), getUserId()))
        {
            return CommonResult.erro("当前用户不能删除");
        }
        return CommonResult.success(userService.deleteUserByIds(ids));
    }

    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwdVue")
    @ResponseBody
    public CommonResult<?> resetPwdSaveVue(@RequestParam("loginName") String loginName, @RequestParam("password") String password,@RequestParam("userId") Integer userId) {
        SysUser user  =  new SysUser();
        user.setPassword(password);
        user.setLoginName(loginName);
        user.setUserId(Long.valueOf(userId));
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        if (userService.resetUserPwd(user) > 0){
            if (ShiroUtils.getUserId().longValue() == user.getUserId().longValue()){
                setSysUser(userService.selectUserById(user.getUserId()));
            }
            return CommonResult.success();
        }
        return CommonResult.erro();
    }

    @PostMapping("/getDeptAndRole")
    @ResponseBody
    public CommonResult<?> getDeptAndRole() {
        Map<String,List<?>> map = new HashMap<>();
        map.put("roles", roleService.selectRoleAll().stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        map.put("posts", postService.selectPostAll());
        map.put("depts", iSysDeptService.selectDeptList(new SysDept()));
        return CommonResult.success(map);
    }

    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/addUserVue")
    @ResponseBody
    public CommonResult<?> addUserVue(@RequestBody @Validated SysUser user) {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName())))
        {
            return CommonResult.erro("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return CommonResult.erro("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return CommonResult.erro("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(getLoginName());
        return CommonResult.success(userService.insertUser(user));
    }
    @PostMapping("/editVue")
    @ResponseBody
    public CommonResult<?> editVue(@RequestParam Long userId) {
        Map<String,List<?>> mmap = new HashMap<>();
        SysUser sysUser = userService.selectUserById(userId);
        List<SysUser> userList= new ArrayList<>();
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        List<SysRole> sysRoles = SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList());
        List<SysPost> sysPosts = postService.selectPostsByUserId(userId);
        List<Long> rold = new   ArrayList<>();
        List<Long> post = new   ArrayList<>();
        sysUser.getRoles().forEach(r->{
            rold.add( r.getRoleId());
        });
        sysUser.getPosts().forEach(p->{
            post.add(p.getPostId());
        });
        sysUser.setRoleIds(rold.toArray(new Long[0]));
        sysUser.setPostIds(post.toArray(new Long[0]));
        userList.add(sysUser);
        mmap.put("user",  userList);
        mmap.put("roles", sysRoles);
        mmap.put("posts", sysPosts);
        return CommonResult.success(mmap);
    }

    @PostMapping("/editUserVue")
    @ResponseBody
    public CommonResult<?> editUserVue( @RequestBody  SysUser user) {
        userService.checkUserAllowed(user);
        //这里不鉴权
//        userService.checkUserDataScope(user.getUserId());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return CommonResult.erro("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return CommonResult.erro("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getLoginName());
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return CommonResult.success(userService.updateUser(user));
    }
}